package com.sky.service.impl;

import com.aliyun.oss.internal.ResponseParsers;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * _*_ coding : utf-8 _*_
 *
 * @Time : 2023/8/3 14:23
 * @Author : 计201任思伟
 * @File : ReportServiceImpl
 * @Project : sky-take-out
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return 查询订单表  已完成的订单
     */
    public TurnoverReportVO getTurnoverStatistic(LocalDate begin, LocalDate end) {
        //查询订单表中已完成的订单
        //生成list集合存放 begin - end 的数据
        List<LocalDate> dateList = getLocalDates(begin, end);
        //将数据存入
        List<Double> turnoverList = new ArrayList<>();
        //查询营业额数据
        for (LocalDate date : dateList) {
            //查询date日期对应的营业额数据，status=5的数据，已完成的订单数据
            //00.00.00
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //23.59.59
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //封装为map  将beginTime endTime status传入
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            //将null转为0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);

        }

        return TurnoverReportVO
                .builder()//lang3 的StringUtils
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistic(LocalDate begin, LocalDate end) {
        //1.创建beginlissst数组存放begin数据
        List<LocalDate> dateList = getLocalDates(begin, end);
        //newUserList 查找新增用户
        List<Integer> newUserList = new ArrayList<>();
        //总用户量
        List<Integer> totalUserList = new ArrayList<>();
        //查找用户表 user 在时间区间内的保存
        for (LocalDate date : dateList) {
            //获取最晚和最早时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //封装为map  先执行total
            Map map = new HashMap<>();
//            map.put("begin",beginTime);
            map.put("end", endTime);
            //总用户数量
            Integer countTotal = userMapper.countByMap(map);

            map.put("begin", beginTime);
            //新增用户数量
            Integer newUser = userMapper.countByMap(map);

            totalUserList.add(countTotal);
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 订单统计接口
     *
     * @param begin
     * @param end
     * @return 有效订单指状态为 “已完成” 的订单
     * 基于可视化报表的折线图展示订单数据，X轴为日期，Y轴为订单数量
     * 根据时间选择区间，展示每天的订单总数和有效订单数
     * 展示所选时间区间内的有效订单数、总订单数、订单完成率，订单完成率 = 有效订单数 / 总订单数 * 100%
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //1.封装dateLisst
        List<LocalDate> dateList = getLocalDates(begin, end);

        //遍历dateList集合 查询每天的有效订单数和订单
        //存放每天的订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天的有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //获取最晚和最早时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的订单总数
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //查询订单总数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //计算时间区间内的订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间内的有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();


    }

    /**
     * 销量排行top10
     *
     * @param begin
     * @param end
     * @return nameList商品名称列表，以逗号分隔
     * numberList销量列表，以逗号分隔
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        // select od.name,SUM(od.number) num from order_detail od,orders o where od.order_id = o.id
        // and o.`status`=5 and order_time > '2023-07-27'  and order_time < '2023-08-27'
        // GROUP BY od.name order by num desc limit 0,10
        //获取最晚和最早时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //通过getsalesTop10方法查询name和number
        //再通过stream流将数据取出
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库获取营业数据  --- 30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //获取00.00.00 - 23.59.59
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);
        //传入 查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin, end);

        //2.通过POI将数据写入excel
        //读取resource下的文件  通过类路径的方式
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //创建新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充数据
            //获取标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+dateBegin+"志"+dateEnd);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            //订单完成率
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //新增用户数
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //第五行有效订单
            row=sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());


            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date=dateBegin.plusDays(i);
                //当天营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(7 + i);
                //行上的单元格
                row.getCell(1).setCellValue(String.valueOf(date));
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());

            }


            //3.通过输出流 将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    /**
     * date获取日期数组
     *
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        //将begin加入到datelist集合
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 根据条件查询订单数量
     *
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);

        return orderMapper.countByMap(map);
    }
}
